let currentPage = 0;
let currentCat = '全部';
let offcanvas_closeButton = document.getElementById("closeButton");
let previousPageButton = document.querySelector('.previousPage');

let playlist_category_button = document.querySelector('.playlist-category-button');
let nextPageButton = document.querySelector('.nextPage');

offcanvas_closeButton.onclick = function () {
    let msk = document.querySelector(".offcanvas-msk")
    msk.setAttribute("style", "display:none");
    window.parent.overflowAuto();
};
playlist_category_button.addEventListener('click', function () {
    let msk = document.querySelector(".offcanvas-msk")
    msk.setAttribute("style", "display:block;");
    if (document.documentElement.clientWidth > 768) {
        window.parent.overflowHidden();
        msk.addEventListener("click", function () {
            offcanvas_closeButton.click();
        })
    }
});
previousPageButton.addEventListener('click', function () {
    currentPage = currentPage - 1;
    axiosGetData();
});
nextPageButton.addEventListener('click', function () {
    currentPage = currentPage + 1;
    axiosGetData();
});
axios.all([getPlayList1(currentPage, currentCat), getPlayListCat()])
    .then(axios.spread(function (res1, res2) {
        buildPlayList(res1);
        buildPlayListCat(res2);
        checkCurrentPage(currentPage);
    })).catch(error => {
    console.log(error);
});

function buildPlayListCat(res) {
    let categories = res.data['categories'];
    let list = Object.values(categories);
    for (let i = 0; i < list.length; i++) {
        let a = list[i];
        if (i === (list.length - 1)) {
            list[i] = '<div style="margin-bottom:180px"><h6 class="mt-3">#' + a + '#</h6><div>';
        } else {
            list[i] = '<div><h6 class="mt-3">#' + a + '#</h6><div>';
        }
    }
    for (let i = 0; i < res.data['sub'].length; i++) {
        let a = res.data['sub'][i];
        let b = list[a['category']];
        list[a['category']] = b + '<button onclick="axiosEveCat(\'' + a['name'] + '\')" type="button" class="btn btn-outline-secondary btn-sm mx-2 mt-2">' + a['name'] + '</button>'
    }
    const playlistcat_body = document.getElementById('playlistcat-body');
    let inText = '';
    for (let i = 0; i < list.length; i++) {
        inText = inText + list[i] + '</div></div>';
    }
    playlistcat_body.innerHTML = inText;
    inText = null;
    list = null;
}

function buildPlayList(res) {
    let playlist_category_name = document.querySelector('.playlist-category-name');
    playlist_category_name.innerText = currentCat;
    for (let i = 0; i < res.data['playlists'].length; i++) {
        const playlist_x = document.getElementById('totalplaylist-playlist-' + (i + 1));
        playlist_x.innerHTML = '<div onclick="jumpPlayListInfo(' + res.data['playlists'][i]['id'] + ',' + res.data['playlists'][i]['trackCount'] + ')" class="playlist-image rounded border-end border-5">\n' +
            '                                    <img class="rounded"\n' +
            '                                         src="' + res.data['playlists'][i]['coverImgUrl'] + '"\n' +
            '                                         alt="">\n' +
            '                                </div>\n' +
            '                                <div onclick="jumpPlayListInfo(' + res.data['playlists'][i]['id'] + ',' + res.data['playlists'][i]['trackCount'] + ')" class="playlist-name">' + limitStringLength(res.data['playlists'][i]['name']) + '</div>\n' +
            '                                <div class="playlist-creator">by&nbsp;<span>' + res.data['playlists'][i]['creator']['nickname'] + '</span></div>\n' +
            '                                <div class="playlist-playcount"><i class="bi bi-headphones"></i>' + changePlayCount(res.data['playlists'][i]['playCount']) + '</div>'
    }
}

function changePlayCount(count) {
    if (parseInt(count) >= 10000) {
        let a = count / 10000;
        return (parseInt(a + "")) + "w";
    } else {
        return count;
    }
}

function checkCurrentPage(pageNumber) {
    let previousPageButton = document.querySelector('.previousPage');
    let nowPageNumber = document.querySelector('.page-now-number');
    nowPageNumber.innerText = (pageNumber + 1);
    if (pageNumber === 0) {
        previousPageButton.classList.add('disabled');
    } else {
        if (previousPageButton.classList.contains('disabled')) {
            previousPageButton.classList.remove('disabled');
        }
    }
}

function getPlayList(offset, cat) {
    return axios.get(`http://localhost:3000/top/playlist?limit=18&order=hot&offset=${offset * 18}&cat=${cat}`);
}

function getPlayList1(offset, cat) {
    if (getQueryString('cat') === null) {
        return axios.get(`http://localhost:3000/top/playlist?limit=18&order=hot&offset=${offset * 18}&cat=${cat}`);
    } else {
        currentCat = getQueryString('cat');
        return axios.get(`http://localhost:3000/top/playlist?limit=18&order=hot&offset=${offset * 18}&cat=${getQueryString('cat')}`);
    }

}

function getPlayListCat() {
    return axios.get('http://localhost:3000/playlist/catlist');
}

function axiosGetData() {
    axios.all([getPlayList(currentPage, currentCat)])
        .then(axios.spread(function (res1) {
            buildPlayList(res1);
            checkCurrentPage(currentPage);
        })).catch(error => {
        console.log(error);
    });
}

function axiosEveCat(cat) {
    currentCat = cat;
    currentPage = 0;
    axiosGetData();
}

function limitStringLength(str) {
    return str.length > 10 ? str.substring(0, 10) + '..' : str;
}

function getQueryString(name) {
    const url_string = window.location.href; // window.location.href
    const url = new URL(url_string);
    return url.searchParams.get(name);
}
